﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XingLucifer.Devices.Inits
{
    public class UT6604 : UT66
    {
        public UT6604(Action<string> action) : base( IBase.Enums.DeviceTypes.UT6604, action)
        {

        }

        public override bool Init(string? sourceIP, string? ip, string? dns, int port)
        {
            if (SetIP(ip, sourceIP))
            {
                if (SetSerialPort(sourceIP))
                {
                    if (SetSocket(sourceIP, port))
                    {
                        return true;
                    }
                    else
                    {
                        _action?.Invoke($"网络通信配置失败");
                    }
                }
                else
                {
                    _action?.Invoke("设置串口失败");
                }
            }
            else
            {
                _action?.Invoke("设置IP失败");
            }
            return false;
        }

        public override bool Reboot()
        {
            return base.Reboot();
        }

        public override bool Ping(string? ip = null)
        {
            try
            {
                return base.Ping(ip);
            }
            catch (Exception)
            {
                return false;
            }
        }

        private bool SetSerialPort(string ip)
        {
            string? str = GetHtml(
                    $"http://{ip}/0200?0=1&1=0&2=9600&3=8&4=1&5=2&6=0&7=1&8=5&9=15&10=0&11=14&12=0&13=1000&14=1&15=5&E=%C8%B7%B6%A8",
                    ip,
                    $"http://{ip}/0200");
            return str?.Contains("DOCTYPE HTML PUBLIC") ?? false;
        }

        private bool SetSocket(string ip, int port)
        {
            string? str = GetHtml(
                    $"http://{ip}/3200?0=1&1=0&2=2&3=6&4=4&5=0&6={port}&7=20&8=8&9=1&10=0.0.0.0&11=0&12=0&13=0&14=0&15=1&16=0.0.0.0&17=0&18=0&19=0&20=0&21=1&22=0.0.0.0&23=0&24=0&25=0&26=0&27=1&28=0.0.0.0&29=0&30=0&31=0&32=0&33=1&34=0.0.0.0&35=0&36=0&37=0&38=0&39=1&40=0.0.0.0&41=0&42=0&43=0&44=0&45=1&46=0.0.0.0&47=0&48=0&49=0&50=0&51=1&52=0.0.0.0&53=0&54=0&55=0&56=0&57=5&E=%C8%B7%B6%A8",
                    ip,
                    $"http://{ip}/0200");
            return str?.Contains("DOCTYPE HTML PUBLIC") ?? false;
        }
    }
}
